/** 
Copyright (c) 2010, Sheikh Abdul Wahid Ahmed
Details @ http://extremecodeworld.codeplex.com/license
**/

using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using EXtremecode.PresentationLayer;
using EXtremecode.BusinessLayer;

public partial class ASCXCombo : System.Web.UI.UserControl,IListControl
{
    private bool isSetDisplayMethodCalled = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    public override string ClientID
    {
        get
        {
            return CurrentClientId;
        }
    }
    protected void Page_PreRender(object sender, EventArgs e)
    {
        vldrRequired.ErrorMessage = string.Format("{0} : {1}",
            caption,ResourceProvider.GetGeneralResourceString("Message_FieldRequired"));



        //Script block
        string currentClientId = this.CurrentClientId;
        string originalClientId = this.OriginalClientId;
        string inputClientId = this.InputClientId;
        string displayClientId = this.DisplayClientId;

        StringBuilder sbScriptBlock = new StringBuilder();

        sbScriptBlock.AppendLine("<script>");

        //succeeded callback function.
        sbScriptBlock.AppendLine(string.Format(@"
        function {0}SucceededCallback(row){{ 
            PopulateCombo({0},row);       
        }}", currentClientId));


        sbScriptBlock.AppendLine(
            string.Format("var {0} = document.getElementById('{0}');", currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.OriginalCtrl = document.getElementById('{1}');",
                currentClientId, originalClientId));

        if (!IsReadOnly)
        {
            sbScriptBlock.AppendLine(
                string.Format("var {0} = document.getElementById('{0}');", inputClientId));

            sbScriptBlock.AppendLine(
               string.Format("{0}.CurrentCtrl = document.getElementById('{1}');",
                   inputClientId, currentClientId));

            combo.Attributes.Add("onchange", onClientChange);
        }


        sbScriptBlock.AppendLine(
            string.Format("{0}.InputCtrl = document.getElementById('{1}');",
            currentClientId, inputClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.DisplayCtrl = document.getElementById('{1}');",
            currentClientId, displayClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.DisplayTextList = new Object();",
            currentClientId));
        foreach (ListItem lItem in combo.Items)
        {
            if (lItem.Value != string.Empty)
            {
                sbScriptBlock.AppendLine(
                    string.Format("{0}.DisplayTextList['{1}'] = '{2}';",
                    currentClientId, lItem.Value, lItem.Text));
            }
        }
        
        
        sbScriptBlock.AppendLine(
            string.Format("{0}.FormattingObject = new EmptyClass();", currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.SetValue = SetComboValue;", currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.GetValue = GetTextValue;", currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.ResetValue = resetValue;", currentClientId));


        sbScriptBlock.AppendLine(
            string.Format("{0}.StringFromat = '{1}';", currentClientId, formatString));

        //these are required for repopulating of Combo by using ajax.
        sbScriptBlock.AppendLine(
            string.Format("{0}.EntityName = '{1}';", currentClientId, entityName));

        sbScriptBlock.AppendLine(
            string.Format("{0}.ReferencedKey = '{1}';", currentClientId, referencedKeyField));

        sbScriptBlock.AppendLine(
            string.Format("{0}.WhereClause = '{1}';",
            currentClientId, whereClause));

        sbScriptBlock.AppendLine(
          string.Format("{0}.SucceededCallback = {0}SucceededCallback;",
          currentClientId));

        sbScriptBlock.AppendLine(
                string.Format("{0}.Repopulate = RepopulateComboAjax;", currentClientId));



        sbScriptBlock.AppendLine(
            string.Format("{0}.FieldNames = '{1}';",
            currentClientId
            , string.Join(",", displayFieldList)));

        sbScriptBlock.AppendLine(
            string.Format("{0}.Key = '{1}';", currentClientId, keyField));




        sbScriptBlock.AppendLine("</script>");

        scriptBlockLiteral.Text = sbScriptBlock.ToString();


        if (!isSetDisplayMethodCalled)
        {
            SetDisplay();
        }

    }



    private void SetDisplay()
    {
        if (IsReadOnly)
        {
            
            label.Text = Text;
            
        }
    }
   

    #region IListControl Members


    private string[] displayFieldList = new string[0];
    public string[] DisplayFieldList
    {
        get
        {
            return displayFieldList; 
        }
        set
        {
            displayFieldList = value;
        }
    }

    public string DisplayFieldListString
    {
        get
        {
            return string.Join(",",displayFieldList);
        }
        set
        {
            displayFieldList = value.Split(',');
        }
    }

    private IEnumerable enumerable;
    public IEnumerable Enumerable
    {
        get
        {
            return enumerable;
        }
        set
        {
            enumerable=value;
        }
    }

    private string onClientChange = string.Empty;
    public string OnClientChange
    {
        get
        {
            return onClientChange;
        }
        set
        {
            onClientChange = value;
        }
    }

    private string formatString;
    public string FormatString
    {
        get
        {
            return formatString;
        }
        set
        {
            formatString=value;
        }
    }

    private string keyField;
    public string KeyField
    {
        get
        {
            return keyField;
        }
        set
        {
            keyField = value;
        }
    }


    private string referencedKeyField;
    public string ReferencedKeyField
    {
        get
        {
            return referencedKeyField;
        }
        set
        {
            referencedKeyField = value;
        }
    }

    
    public new void DataBind()
    {
        combo.Items.Clear();
        combo.Items.Add(new ListItem(ResourceProvider.GetGeneralResourceString("Message_PleaseSelect"), string.Empty));
        if (enumerable is BusinessObjectCollection)
        {
            try
            {
                BusinessObjectCollection boCol = (BusinessObjectCollection)enumerable;
                boCol.SortedBy = string.Join(",", displayFieldList);
                foreach (BusinessObjectPaper boPaper in boCol.GetBOPapers())
                {
                    ListItem lItem = new ListItem();
                    lItem.Value = Convert.ToString(boPaper[keyField]);

                    object[] displayFieldsValues = new object[displayFieldList.Length];
                    for (int i = 0; i < displayFieldList.Length; i++)
                    {
                        object val = boPaper[displayFieldList[i]];
                        displayFieldsValues[i] = (val != null) ? val : string.Empty;
                    }

                    lItem.Text = string.Format(formatString, displayFieldsValues);
                    combo.Items.Add(lItem);
                    
                }
            }
            finally
            {
                ((BusinessObjectCollection)enumerable).Close();        
            }
        }
    }



    #endregion

    #region IASCXControl Members

     public string DisplayCssClass
    {
        get
        {
           return label.CssClass;
        }
        set
        {
            label.CssClass = value;
        }
    }

    private bool isReadOnly = false;
    public bool IsReadOnly
    {
        get
        {
            return isReadOnly;
        }
        set
        {
            isReadOnly = value;
            if (isReadOnly)
            {
                
                multiView.SetActiveView(viewReadOnly);
            }
            else
            {
                multiView.SetActiveView(viewEditable);
            }
        }
    }

    private string whereClause = string.Empty;
    public string WhareClause
    {
        get
        {
            return whereClause;
        }
        set
        {
            whereClause = value;
        }
    }

    
    public object OriginalValue
    {
        get
        {
            string val = hdnOriginal.Value; 
            return (string.IsNullOrEmpty(val)) ?
                null : val;
        }
    }

    public bool HasValueChanged
    {
        get
        {
            return (Value != OriginalValue);
        }
    }

    public object Value
    {
        get
        {
            string val = (isReadOnly && string.IsNullOrEmpty(combo.SelectedValue)) ? hdnCurrent.Value : combo.SelectedValue; 
            return (string.IsNullOrEmpty(val))? 
                null: val;
        }
        set
        {
            try
            {
                if (value == null)
                {
                    value = string.Empty;
                }

                combo.SelectedValue = Convert.ToString(value);
                hdnCurrent.Value = hdnOriginal.Value = combo.SelectedValue;


                SetDisplay();
                isSetDisplayMethodCalled = true;
            }
            finally
            {
            }
           
        }
    }

    public string Text
    {
        get
        {
            string str = string.Empty;
            object val = Value;
            if (val  != null)
            {
                str = combo.Items.FindByValue(val.ToString()).Text;
            }
            return str; 
        }
    }

    public string InputClientId
    {
        get
        {
            return combo.ClientID;
        }
    }
    public string InputUniqueId
    {
        get
        {
            return combo.UniqueID;
        }
    }

    public string DisplayClientId
    {
        get
        {
            return label.ClientID;
        }
    }
    public string DisplayUniqueId
    {
        get
        {
            return label.UniqueID;
        }
    }

    public string OriginalClientId
    {
        get
        {
            return hdnOriginal.ClientID;
        }
    }
    public string CurrentClientId
    {
        get
        {
            return hdnCurrent.ClientID;
        }
    }

    public Control InputControl
    {
        get
        {
            return combo;
        }
    }


    public string JSResetFunction
    {
        get
        {
            return "ResetCombo";
        }
    }

    private bool isRequired = false;
    public bool IsRequired
    {
        get
        {
            return isRequired;
        }
        set
        {
            isRequired = value;
            
            if (isRequired)
            {
                combo.CssClass = "requiredField";
                vldrRequired.Enabled = true;
                vldrRequired.Display = ValidatorDisplay.Dynamic; 
            }
            else
            {
                combo.CssClass = "";
                vldrRequired.Enabled = false;
                vldrRequired.Display = ValidatorDisplay.None;
            }
        }
    }

    private string caption=string.Empty;
    public string Caption
    {
        get
        {
            return caption;
        }
        set
        {
            caption = value;
        }
    }

    private string entityName = string.Empty;
    public string EntityName
    {
        get
        {
            return entityName;
        }
        set
        {
            entityName = value;
        }
    }

    public string ValidationGroup
    {
        get
        {
            return combo.ValidationGroup;
        }
        set
        {
            combo.ValidationGroup =
                vldrRequired.ValidationGroup = value;
        }
    }



    #endregion

 
}
